package com.restkeeper.service;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.restkeeper.config.WeChatConfig;
import com.restkeeper.dto.*;
import com.restkeeper.mapper.*;
import com.restkeeper.model.WxPrepayResp;
import com.restkeeper.model.wx.SendMessageDto;
import com.restkeeper.utils.Result;
import com.restkeeper.utils.ResultCode;
import com.restkeeper.utils.http.HttpUtils;
import com.restkeeper.utils.wx.WeChatUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
//微信h5支付
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.sun.org.apache.xalan.internal.xsltc.compiler.Constants.CHARACTERS;

@Service
@Slf4j
@RequiredArgsConstructor
public class WeChatServiceImpl implements WeChatService{

    private final WeChatConfig weChatConfig;
    private final CommonService commonService;
    private final WeChatSendService weChatSendService;
    private final RedisTemplate redisTemplate;

    @Override
    public String checkSignature(String signature, String timestamp, String nonce, String echostr) {
        String sign_token = weChatConfig.getSign_token();
        // 1.将token、timestamp、nonce三个参数进行字典序排序
        log.info("signature:{},sign_token:{},timestamp:{},nonce:{}", signature, sign_token, timestamp, nonce);
        String sha1 = WeChatUtil.getSha1(sign_token, timestamp, nonce);
        // 2.进行对比
        log.info("随机字符串echostr:{}", echostr);
        log.info("sha1算法得到的字符串:{}", sha1);
        log.info("signature.toUpperCase():{}", signature.toUpperCase());
        System.out.printf("sha1.equals(signature.toUpperCase())=",sha1.equals(signature.toUpperCase()));
        if (sha1.equals(signature.toUpperCase())) {
            return echostr;
        }
        return null;
    }

    @Override
    public Result login(AppLoginDto dto) {
        String jsCode= dto.getCode();
        JSONObject info = commonService.getACCESSInfo(jsCode);
        if (info==null){
            return Result.error(ResultCode.error,"授权失败");
        }
        String ACCESS_TOKEN=info.getString("access_token");
        String openid=info.getString("openid");
        if (StringUtils.isBlank(ACCESS_TOKEN)){
            return Result.error(ResultCode.error,"授权失败");
        }
        if (StringUtils.isBlank(openid)){
            return Result.error(ResultCode.error,"授权失败");
        }
        //得到用户信息之后返回到一个页面
        String url="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID".replace("ACCESS_TOKEN", ACCESS_TOKEN).replace("OPENID", openid);
        String resResult = HttpUtils.sendGet(url);
        JSONObject resJson=JSONObject.parseObject(resResult);
        return Result.ok(resJson);
    }






    @Override
    public Map<String, String> getJsSdkConfig(String url)  {
//        String jsapiTicket = commonService.getJsapiTicket(); // 假设 commonService 有获取 jsapi_ticket 的方法
//        String nonceStr = generateNonceStr();
//        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
//        String signature = WeChatUtil.generateJsSdkSignature(jsapiTicket, nonceStr, timestamp, url);
//
        Map<String, String> config = new HashMap<>();
//        config.put("appId", weChatConfig.getAppId());
//        config.put("timestamp", timestamp);
//        config.put("nonceStr", nonceStr);
//        config.put("signature", signature);
//        config.put("jsApiList", "[\"scanQRCode\"]");

        return config;

    }

    /**
     * 生成随机字符串
     * @return 随机字符串
     */
    public static String generateNonceStr() {
        Random RANDOM = new SecureRandom();
        // 一般 nonceStr 长度为 16 位，可以根据需要调整
        int length = 16;
        StringBuilder nonceStr = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomIndex = RANDOM.nextInt(CHARACTERS.length());
            nonceStr.append(CHARACTERS.charAt(randomIndex));
        }
        return nonceStr.toString();
    }



    /**判断某个时间是否在12个月内
     * @param endDate 到期时间
     * */
    public static boolean isDateWithin12Months(Date endDate) {
        LocalDate givenDate = endDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        // 计算两个日期之间的Period
        Period period = Period.between(givenDate, LocalDate.now());

        // 计算总月份差异
        int totalMonths = Math.abs(period.getYears() * 12 + period.getMonths());

        // 判断是否小于等于12个月
        return totalMonths <= 12;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String callback(Map<String, String> map) {
        String fromUserName = map.get("ToUserName");
        //扫描二维码的用户
        String openid = map.get("FromUserName");
        //二维码内容
        String imei = map.get("ScanResult");
        log.info("==================scanResult============={}",imei);
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if(StringUtils.isNotBlank(fromUserName) && StringUtils.isNotBlank(imei)){


        }

        return "";
    }


}
